﻿using MachineStateOnline.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace MachineStateOnline.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
             addVal = (int)Utilities.EvalFunc.Evaluate(addExpr);
        }
        int addVal = 0;

        public IActionResult Index()
        {
            ViewData["K1URL"] = ConfigManager.GetSection("K1URL");
            ViewData["K2URL"] = ConfigManager.GetSection("K2URL");

            ReadRunDingOffsets();

            var x = int.Parse(ConfigManager.GetSection("OpenLinkMode1or2"));
            if (x == 1)
            {
                ViewData["OpenURLPattern"] = "_self";
            }
            else if (x == 2)
            {
                ViewData["OpenURLPattern"] = "";
            }



            return View();
        }

        private void ReadRunDingOffsets()
        {
            var Sql1 = ConfigManager.GetSection("RunDingOFFSETS");

            var tmpdt = DBHelper.K1ExecSQLReader(Sql1) ?? new DataTable("-127");
            if (tmpdt.TableName != "-127")
            {
                g_daPak.k1RunDingBonus = (int)tmpdt.Rows[0].ItemArray[0];//此处是sql语句
                g_daPak.k2RunDingBonus = (int)tmpdt.Rows[0].ItemArray[1];
            }
            else
            {
                g_daPak.k1RunDingBonus = 0;
                g_daPak.k2RunDingBonus = 0;
            }
            //初始化时 更新一次就好， 每次也要重新读取数据库。
            ViewData["K1RunDingAddition"] = g_daPak.k1RunDingBonus;
            ViewData["K2RunDingAddition"] = g_daPak.k2RunDingBonus;
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });

        }

        //private readonly IConfiguration Configuration;

        int counterGetChart = 0;
        string  addExpr = ConfigManager.GetSection("K1TotalSpindleAdd(expr)");
        public class DataPack
        {
            public int k1RunDingBonus { get; set; }
            public int k2RunDingBonus { get; set; }
        }

        DataPack g_daPak = new DataPack();

        int jumpFirst = 0;
        /// <summary>
        /// 获取数据并返回到前端
        /// </summary>
        /// <returns></returns>
        public IActionResult GetAllCharts(DataPack dpk)
        {
            //为了 网页 上更新 偏移量
            //var sql001 = "UPDATE Run_Offsets SET NO1 = 0, NO2=0";
            //UpdateK1K2Offsets(sql001);

            //只需要一科电脑 上的。。
            var Sql1 = ConfigManager.GetSection("RunDingOFFSETS");

            var tmpdt = DBHelper.K1ExecSQLReader(Sql1) ?? new DataTable("-127");
            if (tmpdt.TableName != "-127")
            {
                dpk.k1RunDingBonus = (int)tmpdt.Rows[0].ItemArray[0];//此处是sql语句
                dpk.k2RunDingBonus = (int)tmpdt.Rows[0].ItemArray[1];
            }
            else
            {
                dpk.k1RunDingBonus = 0;
                dpk.k2RunDingBonus = 0;
            }

            

            var K1Result = new object();
            var K2Result = new object();

            bool K1GetDataSuccess = false;
            bool K2GetDataSuccess = false;

            List<object> k1rate = new List<object>();
            List<object> k2rate = new List<object>();
            List<object> kAllrate = new List<object>();

            List<object> k1Detail = new List<object>();
            List<object> k2Detail = new List<object>();
            List<object> kAllDetail = new List<object>();

            ChartData k1CD = new ChartData(0, 0, 0, 0);
            ChartData k2CD = new ChartData(0, 0, 0, 0);
            var iDiTotal1 = 0;
            var iDiTotal2 = 0;

            if (!DBHelper.K1ConnFailureTag)
            {
                var tmp = GetK1ChartData(k1CD);

                if (tmp.IsGetDataSuccessed)
                {
                    k1CD.运行锭数 = (int)tmp.Table_RunningSpindle.Rows[0].ItemArray[0];
                    k1CD.停止锭数 = (int)tmp.Table_StopSpindle.Rows[0].ItemArray[0];
                    k1CD.满锭数 = (int)tmp.Table_FullSpindle.Rows[0].ItemArray[0];
                    k1CD.故障锭数 = (int)tmp.Table_AlarmSpindle.Rows[0].ItemArray[0];

                    //修正 5台 力达的。没装上去。

                    //k1CD.运行锭数 += 5 * 168;
                    //k1CD.停止锭数 -= 5 * 168;


                    iDiTotal1 = (k1CD.运行锭数 + k1CD.停止锭数 + k1CD.满锭数 + k1CD.故障锭数);

                    var RunRate = (float)Math.Round((float)(k1CD.运行锭数 + k1CD.满锭数) / iDiTotal1 * 100, 2);
                    var NoRunRate = (float)Math.Round((float)(iDiTotal1 - (k1CD.运行锭数 + k1CD.满锭数)) / iDiTotal1 * 100, 2);

                    //k1rate.Add(new { name = "开动率", value = RunRate });
                    //k1rate.Add(new { name = "停止率", value = StopRate });
                    //k1rate.Add(new { name = "故障率", value = AlarmRate });
                    //k1rate.Add(new { name = "完成率", value = FinishRate });
                    k1rate.Add(new { name = "开动率", value = RunRate });
                    k1rate.Add(new { name = "非开动率", value = NoRunRate });


                    k1Detail.Add(new { name = "运行中", value = k1CD.运行锭数 });
                    k1Detail.Add(new { name = "满锭数", value = k1CD.满锭数 });

                    //组态王 发过来的数据有1000多个, 减去800多个。
                    k1Detail.Add(new { name = "停机数", value = k1CD.停止锭数 });
                    k1Detail.Add(new { name = "报警数", value = k1CD.故障锭数 });

                    K1GetDataSuccess = true;



                }
                else
                {
                    k1rate.Add(new { name = "开动率", value = -1 });
                    k1rate.Add(new { name = "非开动率", value = -1});

                    k1Detail.Add(new { name = "运行中", value = 0 });
                    k1Detail.Add(new { name = "满锭数", value = 0 });
                    k1Detail.Add(new { name = "停机数", value = 0 });
                    k1Detail.Add(new { name = "报警数", value = 0 });
                    K1GetDataSuccess = false;

                }

            }
            else
            {
                k1rate.Add(new { name = "开动率", value = -1 });
                k1rate.Add(new { name = "非开动率", value = -1 });

                k1Detail.Add(new { name = "运行中", value = 0 });
                k1Detail.Add(new { name = "满锭数", value = 0 });
                k1Detail.Add(new { name = "停机数", value = 0 });
                k1Detail.Add(new { name = "报警数", value = 0 });
                K1GetDataSuccess = false;
            }

            if (!DBHelper.K2ConnFailureTag)
            {

                var tmp = GetK2ChartData(k2CD);
                if (tmp.IsGetDataSuccessed)
                {
                    k2CD.运行锭数 = (int)tmp.Table_RunningSpindle.Rows[0].ItemArray[0];
                    k2CD.停止锭数 = (int)tmp.Table_StopSpindle.Rows[0].ItemArray[0];
                    k2CD.满锭数 = (int)tmp.Table_FullSpindle.Rows[0].ItemArray[0];
                    k2CD.故障锭数 = (int)tmp.Table_AlarmSpindle.Rows[0].ItemArray[0];

                    iDiTotal2 = k2CD.运行锭数 + k2CD.停止锭数 + k2CD.满锭数 + k2CD.故障锭数;
                    var RunRate = (float)Math.Round((float)(k2CD.运行锭数 + k2CD.满锭数) / iDiTotal2 * 100, 2);
                    var StopRate = (float)Math.Round((float)k2CD.停止锭数 / iDiTotal2 * 100, 2);
                    var AlarmRate = (float)Math.Round((float)k2CD.故障锭数 / iDiTotal2 * 100, 2);
                    var FinishRate = (float)Math.Round((float)k2CD.满锭数 / iDiTotal2 * 100, 2);

                    var NoRunRate = Math.Round(100 - RunRate, 2);

                    k2rate.Add(new { name = "开动率", value = RunRate });
                    k2rate.Add(new { name = "非开动率", value = NoRunRate });
                    //k2rate.Add(new { name = "开动率", value = RunRate });
                    //k2rate.Add(new { name = "停止率", value = StopRate });
                    //k2rate.Add(new { name = "故障率", value = AlarmRate });
                    //k2rate.Add(new { name = "完成率", value = FinishRate });



                    k2Detail.Add(new { name = "运行中", value = k2CD.运行锭数 });
                    k2Detail.Add(new { name = "满锭数", value = k2CD.满锭数 });
                    k2Detail.Add(new { name = "停机数", value = k2CD.停止锭数 });
                    k2Detail.Add(new { name = "报警数", value = k2CD.故障锭数 });

                    K2GetDataSuccess = true;
                }
                else
                {
                    k2rate.Add(new { name = "开动率", value = -1 });
                    k2rate.Add(new { name = "非开动率", value = -1 });
                    k2Detail.Add(new { name = "运行中", value = 0 });
                    k2Detail.Add(new { name = "满锭数", value = 0 });
                    k2Detail.Add(new { name = "停机数", value = 0 });
                    k2Detail.Add(new { name = "报警数", value = 0 });
                    K2GetDataSuccess = false;

                }
            }
            else
            {
                k2rate.Add(new { name = "开动率", value = -1 });
                k2rate.Add(new { name = "非开动率", value = -1 });
                k2Detail.Add(new { name = "运行中", value = 0 });
                k2Detail.Add(new { name = "满锭数", value = 0 });
                k2Detail.Add(new { name = "停机数", value = 0 });
                k2Detail.Add(new { name = "报警数", value = 0 });
                K2GetDataSuccess = false;
            }

            if (K2GetDataSuccess && K1GetDataSuccess)
            {

                float RunRate1 = -1;
                float StopRate1 = -1;
                float AlarmRate1 = -1;
                float FinishRate1 = -1;

                float RunRate2 = -1;
                float StopRate2 = -1;
                float AlarmRate2 = -1;
                float FinishRate2 = -1;

                var kAll运行锭数 = k1CD.运行锭数 + k2CD.运行锭数;
                var kAll满锭数 = k1CD.满锭数 + k2CD.满锭数;
                var kAll停止锭数 = k1CD.停止锭数 + k2CD.停止锭数;
                var kAll故障锭数 = k1CD.故障锭数 + k2CD.故障锭数;

                if (iDiTotal1 > 0 && iDiTotal2 > 0)
                {


                    RunRate1 = (float)Math.Round((float)k1CD.运行锭数 / iDiTotal1 * 100, 3);
                    StopRate1 = (float)Math.Round((float)k1CD.停止锭数 / iDiTotal1 * 100, 2);
                    AlarmRate1 = (float)Math.Round((float)k1CD.故障锭数 / iDiTotal1 * 100, 2);
                    FinishRate1 = (float)Math.Round((float)k1CD.满锭数 / iDiTotal1 * 100, 2);

                    RunRate2 = (float)Math.Round((float)k2CD.运行锭数 / iDiTotal2 * 100, 3);
                    StopRate2 = (float)Math.Round((float)k2CD.停止锭数 / iDiTotal2 * 100, 2);
                    AlarmRate2 = (float)Math.Round((float)k2CD.故障锭数 / iDiTotal2 * 100, 2);
                    FinishRate2 = (float)Math.Round((float)k2CD.满锭数 / iDiTotal2 * 100, 2);

                    //var NoRunRate = ((StopRate1 + StopRate2) / 2 + (AlarmRate1 + AlarmRate2) / 2 + (FinishRate1 + FinishRate2) / 2);

                    var AllDing = kAll运行锭数 + kAll满锭数 + kAll停止锭数 + kAll故障锭数;
                    decimal AllRunRate = (decimal)Math.Round((float)(kAll运行锭数 + kAll满锭数) / AllDing, 4);

                    var NotAllRunRate = Math.Round(1 - AllRunRate, 4);

                    kAllrate.Add(new { name = "开动率", value = AllRunRate * 100 });
                    kAllrate.Add(new { name = "非开动率", value = NotAllRunRate * 100 });

                    //kAllrate.Add(new { name = "总开动率", value = (RunRate1 + RunRate2) / 2 });
                    //kAllrate.Add(new { name = "总停止率", value = (StopRate1 + StopRate2) / 2 });
                    //kAllrate.Add(new { name = "总故障率", value = (AlarmRate1 + AlarmRate2) / 2 });
                    //kAllrate.Add(new { name = "总完成率", value = (FinishRate1 + FinishRate2) / 2 });

                    kAllDetail.Add(new { name = "运行中", value = kAll运行锭数 });
                    kAllDetail.Add(new { name = "满锭数", value = kAll满锭数 });
                    kAllDetail.Add(new { name = "停机数", value = kAll停止锭数 });
                    kAllDetail.Add(new { name = "报警数", value = kAll故障锭数 });
                }
                else
                {
                    kAllrate.Add(new { name = "开动率", value = -1 });
                    kAllrate.Add(new { name = "非开动率", value = -1 });

                    kAllDetail.Add(new { name = "运行中", value = 0 });
                    kAllDetail.Add(new { name = "满锭数", value = 0 });
                    kAllDetail.Add(new { name = "停机数", value = 0 });
                    kAllDetail.Add(new { name = "报警数", value = 0 });
                }
            }


            if ((!K2GetDataSuccess) || (!K1GetDataSuccess))
            {
                kAllrate.Add(new { name = "开动率", value = -1 });
                kAllrate.Add(new { name = "非开动率", value = -1 });
                kAllDetail.Add(new { name = "运行中", value = 0 });
                kAllDetail.Add(new { name = "满锭数", value = 0 });
                kAllDetail.Add(new { name = "停机数", value = 0 });
                kAllDetail.Add(new { name = "报警数", value = 0 });
            }

            counterGetChart++;
            if (counterGetChart > 98)
                counterGetChart = 0;



            var Result = new
            {
                k1rate,
                k2rate,
                kAllrate,
                fps = "FpS:" + counterGetChart,
                k1Detail,
                k2Detail,
                kAllDetail,
                dpk
            };





            return Json(Result);//返回JSON数据
        }

        private static void UpdateK1K2Offsets(string sql001)
        {
            DBHelper.K1ExeNotRead(sql001);
        }

        private static RetDataPack GetK2ChartData(ChartData dt)
        {
            var Sql1 = ConfigManager.GetSection("RunningSpindleSQL");
            var Sql2 = ConfigManager.GetSection("StopSpindleSQL");
            var Sql3 = ConfigManager.GetSection("FullSpindleSQL");
            var Sql4 = ConfigManager.GetSection("AlarmSpindleSQL");
            var Sql5 = ConfigManager.GetSection("TestSQL");
            RetDataPack pak = new RetDataPack();
            pak.Table_RunningSpindle = DBHelper.K2ExecSQLReader(Sql1) ?? new DataTable("-1");//此处是sql语句
            pak.Table_StopSpindle = DBHelper.K2ExecSQLReader(Sql2) ?? new DataTable("-1");//此处是sql语句
            pak.Table_FullSpindle = DBHelper.K2ExecSQLReader(Sql3) ?? new DataTable("-1");//此处是sql语句
            pak.Table_AlarmSpindle = DBHelper.K2ExecSQLReader(Sql4) ?? new DataTable("-1");//此处是sql语句
            //var TestSQL = DBHelper.K2ExecSQLReader(Sql5);

            var PaiChartData = new List<object>();
            if (pak.Table_RunningSpindle == null || pak.Table_StopSpindle == null || pak.Table_FullSpindle == null || pak.Table_AlarmSpindle == null)
            {
                pak.IsGetDataSuccessed = false;
            }
            else
            {
                pak.IsGetDataSuccessed = true;
            }
            return pak;
        }

        private static RetDataPack GetK1ChartData(ChartData dt)
        {
            var Sql1 = ConfigManager.GetSection("RunningSpindleSQL");
            var Sql2 = ConfigManager.GetSection("StopSpindleSQL");
            var Sql3 = ConfigManager.GetSection("FullSpindleSQL");
            var Sql4 = ConfigManager.GetSection("AlarmSpindleSQL");
            var Sql5 = ConfigManager.GetSection("TestSQL");
            RetDataPack pak = new RetDataPack();
            pak.Table_RunningSpindle = DBHelper.K1ExecSQLReader(Sql1) ?? new DataTable("-1");//此处是sql语句
            pak.Table_StopSpindle = DBHelper.K1ExecSQLReader(Sql2) ?? new DataTable("-1");//此处是sql语句
            pak.Table_FullSpindle = DBHelper.K1ExecSQLReader(Sql3) ?? new DataTable("-1");//此处是sql语句
            pak.Table_AlarmSpindle = DBHelper.K1ExecSQLReader(Sql4) ?? new DataTable("-1");//此处是sql语句
            var PaiChartData = new List<object>();


            if (pak.Table_RunningSpindle == null || pak.Table_StopSpindle == null || pak.Table_FullSpindle == null || pak.Table_AlarmSpindle == null)
            {
                pak.IsGetDataSuccessed = false;
            }
            else
            {
                pak.IsGetDataSuccessed = true;
            }


            return pak;
        }
    }
}

